#!/usr/bin/env python
import single_process.init
from decimal import Decimal
from acora import AcoraBuilder
from tz.util.rate_by_day import rate_by_day
from _ratio import save_dividend_ratio
from tz.util.txt import RE_NUMBER
from tz.db.pg import PG
from tz.util.day import str2day, day2str
from tz.util.currency import CURRENCY2SYMBOL, AC

ACTION = {}


def main():
    # event_count = PG.query(
    #     "select action,count(1) from stock.com_event where country=%s group by action", 'HK'
    # )
    # for i in event_count:
    #     print(i)
    for event in PG.iter('stock.com_event', where={'country': 'HK'}):
        func = ACTION.get(event.action, 0)
        if func:
            func(event.com_id, event.day, event.txt)
        else:
            pass
        # print(">>> ACTION NOT FOUND", event.action)


def action(func):
    ACTION[func.__name__] = func
    return func


@action
def 股息(com_id, day, txt):
    num_li = RE_NUMBER.findall(txt)
    if not num_li:
        return

    if txt.startswith('港币'):
        money = num_li[0]
    else:
        currency_li = [i[0] for i in AC.findall(txt)]
        if len(num_li) != len(currency_li):
            if '实物' not in txt:
                print(num_li)
                print(currency_li)
                print(txt)
                print()
            return
        else:
            money = 0
            for currency, num in zip(currency_li, num_li):
                if currency == '港币':
                    money = num

            if not money:
                for currency, num in zip(currency_li, num_li):
                    if currency in CURRENCY2SYMBOL:
                        symbol = CURRENCY2SYMBOL[currency]
                        num = Decimal(num)
                        rate = rate_by_day(day, symbol, 'HKD')
                        money = rate * num

    if not money:
        print(txt)
        return

    money = Decimal(money)
    save_dividend_ratio(
        com_id, day,
        money
    )


ACTION['特别股息'] = 股息

# ACTION = {} #TODO 注释掉！！！


def _split(split):
    def _(com_id, day, txt):
        num_li = RE_NUMBER.findall(txt)
        if not len(num_li) == 2:
            print(com_id, day, txt)
            return
        from_stock, to_stock = tuple(map(Decimal, num_li))

        save_dividend_ratio(
            com_id, day,
            0,
            split(from_stock, to_stock)
        )
    return _


# @action
# def 合并(com_id, day, txt):
# if com_id == 5049:
#     print(split, to_stock, from_stock, day, day2str(day), txt)
#     input()


ACTION['股份拆细'] = ACTION['合并'] = _split(
    lambda from_stock, to_stock: to_stock / from_stock
)
ACTION['红股'] = _split(
    lambda base_stock, send_stock: (
        1 + send_stock / base_stock
    )
)

if __name__ == "__main__":
    import hk
    hk.main()
    main()
